package com.probox.common.core.validator;

import com.probox.common.core.annotation.LongLength;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author panmou
 * @date 2022-05-18
 * 用于实现任何长度的校验
 */
public class LongLengthValidator implements ConstraintValidator<LongLength, Long> {

    // 最小长度
    private int min;

    // 最大长度
    private int max;

    private String message;

    /**
     * 初始化获取注解的值
     *
     * @param constraintAnnotation
     */
    @Override
    public void initialize(LongLength constraintAnnotation) {
        min = constraintAnnotation.min();
        max = constraintAnnotation.max();
        message = constraintAnnotation.message();
    }

    /**
     * 初始化获取注解的值
     *
     * @param value   要校验的字段值
     * @param context 校验上下文
     * @return true校验通过/false校验失败
     */
    @Override
    public boolean isValid(Long value, ConstraintValidatorContext context) {
        //禁用默认提示信息
        context.disableDefaultConstraintViolation();
        String s = String.valueOf(value);
        if (min > s.length()) {
            //设置提示语
            context.buildConstraintViolationWithTemplate(message + "长度不符合,最小为" + min + "位！").addConstraintViolation();
            return false;
        }
        if (max < s.length()) {
            //设置提示语
            context.buildConstraintViolationWithTemplate(message + "长度不符合,最大为" + max + "位！").addConstraintViolation();
            return false;
        }
        return true;
    }
}
